package cn.jinjimi.app.main.widget.FrescoImageView;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.baiiu.filter.util.UIUtil;
import com.facebook.imagepipeline.request.BaseRepeatedPostProcessor;

import java.io.ByteArrayOutputStream;

/**
 * Created by lforxeverc on 2017/6/28.
 */

public class CutImageProcessor extends BaseRepeatedPostProcessor {

    private Context mContext;
    private int mHighDp;

    public CutImageProcessor(Context mContext, int mHighDp) {
        this.mContext = mContext;
        this.mHighDp = mHighDp;
    }

    @Override
    public void process(Bitmap bitmap) {
        if (mHighDp > 0) {
            bitmap = bitmapDeal(bitmap);
        }
        super.process(bitmap);
    }


    // 压缩图片质量以及截取
    private Bitmap bitmapDeal(Bitmap bitmap) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            // 1.计算出来图片的宽高.
            BitmapFactory.Options opts = new BitmapFactory.Options();
            // 2.设置 不去真正的解析位图 不把他加载到内存 只是获取这个图片的宽高信息
            opts.inJustDecodeBounds = true;
            byte[] bytes = baos.toByteArray();
            BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
            int bitmapHeight = opts.outHeight;
            int bitmapWidth = opts.outWidth;
            int destH = UIUtil.dp(mContext, mHighDp);
            if (bitmapHeight > destH) {
                // 3.压缩图片质量
                bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);
                opts.inPreferredConfig = Bitmap.Config.RGB_565;
                // 4.让位图工厂真正的去解析图片
                opts.inJustDecodeBounds = false;
                bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opts);
                // 5.图片截取并返回
                return Bitmap.createBitmap(bitmap, 0, bitmapHeight - destH, bitmapWidth, destH);
            } else {
                return bitmap;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }
}
